<?php
/**
 * BaseApi
 *
 * PHP Version 5.4
 *
 * @author liuxuTJ <liuxuphp@icesmart.cn>
 */
namespace Api\Controller;

use Model\InterfaceModel;
use Model\UserModel;
use Think\Controller;
use Think\Page;
use Think\Upload;

/**
 * Class BaseController
 */
class BaseController extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 验证用户是否登录
     *
     * @method COOKIE
     *
     * @return String
     */
    public function validateLogin()
    {
        $userId = cookie('userId');
        if (empty($userId)) {
            $this->error('请先登录', __ROOT__ . '/Admin/User/index.html', 1);
        }

        $userModel = new UserModel();
        $userInfo = $userModel->get($userId);

        $userInfo = ['userId' => $userId, 'username' => $userInfo['username'], 'lastIp' => $userInfo['lastIp'], 'lastTime' => $userInfo['lastTime']];

        return $userInfo;
    }

    /**
     * 对象转数组
     */
    function object_to_array($stdclassobject)
    {
        $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;

        $array = [];
        foreach ($_array as $key => $value) {
            $value = (is_array($value) || is_object($value)) ? $this->object_to_array($value) : $value;
            $array[$key] = $value;
        }

        return $array;
    }

    /**
     * 验证接口
     */
    public function validateInterface($url)
    {
        $interfaceModel = new InterfaceModel();
        $interfaceInfo = $interfaceModel->where('url = "' . $url . '"')->find();
        if ($interfaceInfo['status'] == 1) {
            $createTime = date('Y-m-d H:i:s');
            $interfaceModel->where('id = ' . $interfaceInfo['id'])->setInc('visits', 1);
            $interfaceModel->where('id = ' . $interfaceInfo['id'])->setField('lastTime', $createTime);

            return true;
        } else {
            return false;
        }
    }


    function callInterfaceCommon($URL, $type, $params, $headers)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $URL); //发贴地址
        if ($headers != "") {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: text/json']);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        switch ($type) {
            case "GET" :
                curl_setopt($ch, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                break;
            case "PUT" :
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                break;
            case "DELETE":
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
                break;
        }
        $file_contents = curl_exec($ch);//获得返回值
        return $file_contents;
        curl_close($ch);
    }

    /**
     * 获取时间（几分钟前、几小时前）
     */
    public function time_tran($the_time)
    {
        $now_time = date("Y-m-d H:i:s", time());
        //echo $now_time;
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) {//3天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            return $the_time;
                        }
                    }
                }
            }
        }
    }

    /**
     *  上传文件
     *
     * @method POST
     *
     */
    public function upload($file)
    {
        $upload = new Upload();
        $upload->maxSize = 1 * 1024 * 1024;  //设置附件上传大小
        $upload->exts = ['jpg', 'gif', 'png', 'jpeg']; //设置附件上传类型
        $upload->savePath = '/Uploads/';
        $upload->rootPath = './Images/';   //设置上传目录
        $upload->saveName = time() . '_' . mt_rand();

        $result = $upload->uploadOne($file);
        if (!$result) {
            $this->AlertBack($upload->getError());
        } else {
            return 'Images' . $result['savepath'] . $result['savename'];
        }
    }

    /**
     *  上传多个文件
     *
     * @method POST
     *
     */
    public function uploadList($file, $size)
    {
        $upload = new Upload();
        $upload->maxSize = $size * 1024;  //设置附件上传大小
        $upload->exts = ['jpg', 'gif', 'png', 'jpeg']; //设置附件上传类型
        $upload->savePath = '/Uploads/';
        $upload->rootPath = './Images/';   //设置上传目录

        $imageFileRest = [];
        /*** 重新整理上传图片 ***/
        for ($i = 0; $i < count($file['name']); $i++) {
            $imageFileRest[$i]['name'] = $file['name'][$i];
            $imageFileRest[$i]['type'] = $file['type'][$i];
            $imageFileRest[$i]['tmp_name'] = $file['tmp_name'][$i];
            $imageFileRest[$i]['error'] = $file['error'][$i];
            $imageFileRest[$i]['size'] = $file['size'][$i];
        }

        $image = '';
        foreach ($imageFileRest as $img) {
            $upload->saveName = time() . '_' . mt_rand();
            if ($img['size'] > $upload->maxSize) {
                $this->AlertBack('单张图片限制' . $size . 'KB以内');
            } else {
                $result = $upload->uploadOne($img);
                if (!$result) {
                    $this->error($upload->getError(), null, 2);
                } else {
                    $image = $image . 'Images' . $result['savepath'] . $result['savename'] . ' ';
                }
            }
        }

        return $image;
    }

    /**
     *  获取分页
     *
     * @method POST
     *
     */
    public function page($model, $where, $pagesize = 10)
    {
        $modelClone = clone $model;
        $count = $model->where($where)->count();
        $model = $modelClone;
        $page = new Page($count, $pagesize);

        $page->parameter = I('get.');

        $model->limit($page->firstRow . ',' . $page->listRows);

        return $page;
    }

    public function AlertBack($_msg)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "history.go(-1);";
        echo "</script>";
        exit();
    }

    public function AlertGoToUrl($_msg, $_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "alert('" . $_msg . "');";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }

    public function Alert($_url)
    {
        header("Content-Type:text/html; charset=utf-8");
        echo "<script type=\"text/javascript\">";
        echo "window.location.href='" . $_url . "'";
        echo "</script>";
        exit();
    }
}